﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Maxleaf.EDI.API.Contract;
using Maxleaf.EDI.API.Contract.K3.Commands;
using Maxleaf.EDI.Client.Models;
using MvcFileUploader;
using MvcFileUploader.Models;

namespace Maxleaf.EDI.Client.Controllers
{
    public class ImportSalesOrderController : Controller
    {
        private readonly IClientService clientService;
        private readonly IK3Service k3Service;

        public ImportSalesOrderController()
        {
            this.k3Service = TinyIoC.TinyIoCContainer.Current.Resolve<IK3Service>();
            this.clientService = TinyIoC.TinyIoCContainer.Current.Resolve<IClientService>();
        }

        [Authorize]
        public ActionResult Index()
        {
            var dbs = this.clientService.GetUserDBs(new Maxleaf.EDI.API.Contract.Client.Parameters.GetUserDBsParameters {UserName=this.User.Identity.Name });

            ViewBag.DBs = dbs.DBs.Select(db => new DBInfoModel { DBId=db.DBId,DBName=db.DBName,FInterId=db.FInterId }).ToList();
            return View();
        }
        
        [Authorize]
        public ActionResult UploadFile(string dbId) // optionally receive values specified with Html helper
        {
            // here we can send in some extra info to be included with the delete url 
            var statuses = new List<ViewDataUploadFileResult>();

            for (var i = 0; i < Request.Files.Count; i++)
            {

                var path = Server.MapPath(string.Format("~/Content/uploads/{0}/SalesOrder/", DateTime.Now.ToString("yyyyMMdd")));
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                var fileName = Request.Files[i].FileName.Split('\\').Last();
                var fullFileName=Path.Combine(path, fileName);
                if (System.IO.File.Exists(fullFileName))
                {
                    statuses.Add(new ViewDataUploadFileResult { name = fileName, error = "同名文件已上传过" });
                }
                else
                {
                    if (!string.IsNullOrEmpty(dbId))
                    {
                        var st = FileSaver.StoreFile(x =>
                        {
                            x.File = Request.Files[i];
                            //note how we are adding an additional value to be posted with delete request
                            //and giving it the same value posted with upload
                            x.DeleteUrl = string.Empty;
                            x.StorageDirectory = path;
                            x.UrlPrefix = "/Content/uploads";


                            //overriding defaults
                            x.FileName = fileName;// default is filename suffixed with filetimestamp
                            x.ThrowExceptions = false;//default is false, if false exception message is set in error property
                        });


                        try
                        {
                            this.k3Service.Import(new ImportSalesOrderCommand { DBId = dbId, FileName = fullFileName });
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                System.IO.File.Delete(fullFileName);
                            }
                            catch { }
                            st.error = ex.Message;
                        }


                        statuses.Add(st);
                    }
                    else
                    {
                        statuses.Add(new ViewDataUploadFileResult { name = fileName, error = "无效帐套" });
                    }
                }

            }


            return Json(new { files = statuses }, "text/html");
        }

    }
}
